
import { _decorator, Component, Node, SpriteFrame, Tween, Sprite, Vec3, find,sys } from 'cc';
import { getNet } from './Other/Util';
import { Switch } from './Switch';
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = CardReverser
 * DateTime = Wed Feb 02 2022 18:11:52 GMT+0800 (中国标准时间)
 * Author = awi1299
 * FileBasename = CardReverser.ts
 * FileBasenameNoExtension = CardReverser
 * URL = db://assets/script/CardReverser.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */

@ccclass('CardReverser')
export class CardReverser extends Component {
    // [1]
    // dummy = '';

    // [2]
    // @property
    // serializableDummy = 0;
    @property(SpriteFrame)
    cardFront

    @property(SpriteFrame)
    cardBack

    isFront = false
    isExpose = false

    start() {
        this.node.on(Node.EventType.TOUCH_END, this.change, this);
    }

    /**
     * 翻牌函数
     * @returns null
     */
    change(){
        //如果现在是自己看的状态，就不能翻牌
        if(!find('Canvas/Switch').getComponent(Switch).isPublic)return 
        
        //翻牌
        console.log('expose state change')
        this.isExpose = !this.isExpose
        if(this.isExpose)this.toFront()
        else this.toBack()

        //同步服务端状态
        const net = getNet()
        net.room.send('card',this.name)
    }

    toFront() {
        this.isFront = true
        this.reverse()
    }

    toBack() {
        this.isFront = false
        this.reverse()
    }

    private reverse() {
        const reverseTime = 0.5
        new Tween(this.node)
            .to(reverseTime, { eulerAngles: new Vec3(0, 90, 0) }, {
                easing: 'quadIn', onStart: () => {
                    this.node.pauseSystemEvents(true)
                }
            })
            .call(() => {
                const cardSprite = this.getComponent(Sprite)
                if (this.isFront) {
                    cardSprite.spriteFrame = this.cardFront
                } else {
                    cardSprite.spriteFrame = this.cardBack
                }
            })
            .to(reverseTime / 2, { eulerAngles: new Vec3(0, 360, 0) }, {
                easing: 'quadOut', onComplete: () => {
                    this.node.resumeSystemEvents(true)
                }
            })
            .union()
            .start()
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/zh/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/zh/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/zh/scripting/life-cycle-callbacks.html
 */
